package com.parse.core;

import android.app.Activity;
import android.util.Log;

import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import com.parse.PaException.PaException;
import com.parse.api.AddProduceService;
import com.parse.api.Padelegate;
import com.parse.api.ParserUtils;
import com.parse.bean.AddProduceDTO;
import com.parse.contract.Msg;
import com.parse.domain.Produce;

/**
 * 新增商品服務
 * 
 * @author Andy
 * 
 */
public class AddProduceServiceImpl implements AddProduceService {

	protected static final String TAG = AddProduceServiceImpl.class.getName();

	private transient ParserUtils parserUtils;

	private transient Padelegate padelegate;

	public AddProduceServiceImpl() {
		parserUtils = new ParserUtilsImpl();

	}

	@Override
	public void uploadProduce(final AddProduceDTO dto, final Activity activity) {

		final Produce produce = new Produce();

		produce.setName(dto.getTitle());
		produce.setPrice(dto.getPrice());
		produce.setDescribe(dto.getDescribe());

		ParseFile file = new ParseFile(ParseUser.getCurrentUser().getObjectId()
				+ ".jpg", dto.getPicBytes());

		this.padelegate = (Padelegate) activity;

		final ParseObject parseObject = this.parserUtils
				.makeParseObject(produce);
		parseObject.put("pic", file);

		parseObject.saveInBackground(new SaveCallback() {

			@Override
			public void done(ParseException e) {

				if (e == null) {
					getPadelegate().putMessage(
							AddProduceServiceImpl.class.getSimpleName(),
							"新增完成", null);
				} else {
					Log.e(TAG, e.getMessage());
					getPadelegate().putMessage(
							AddProduceServiceImpl.class.getSimpleName(), "",
							new PaException(Msg.PASER_ERROR001));
				}

			}
		});

	}

	public Padelegate getPadelegate() {
		return padelegate;
	}

	public void setPadelegate(Padelegate padelegate) {
		this.padelegate = padelegate;
	}

	public ParserUtils getParserUtils() {
		return parserUtils;
	}

	public void setParserUtils(ParserUtils parserUtils) {
		this.parserUtils = parserUtils;
	}

}
